<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleTabChange">
      <el-tab-pane label="积分获取" name="积分获取">
        <el-form :model="getFormData" :rules="getRules" ref="getFormData" :inline="true" size="mini">
          <el-form-item label="" label-width="0"><b>积分方式：</b></el-form-item>
          <el-form-item label="" label-width="0">
            <el-radio-group v-model="getFormData.integralType" @change="handleChangeIntegralType">
              <el-radio label="0" value="0">按消费金额</el-radio>
              <el-radio label="1" value="1">按商品积分</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>

        <!--按消费金额-->
        <div v-show="getFormData.integralType == 0">
          <el-form :model="getFormData" :rules="getRules" ref="getFormData" :inline="true" size="mini">
            <el-form-item label="消费" prop="amount">
              <el-input onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''" type="text" v-model="getFormData.amount"></el-input>
            </el-form-item>
            <el-form-item label="" label-width="0">元，积 1 分</el-form-item>
            <div>
              <el-form-item label="" label-width="0"><span>不参加积分商品</span></el-form-item>
              <el-form-item label="" label-width="0">
                <el-button type="primary" @click="clickAddGoodsByMoney()">添加 </el-button>
              </el-form-item>
            </div>
            <div class="tableMain">
              <el-table :data="tableDataByMoney" ref="tableDataByMoney" style="width: 100%" height="300">
                <el-table-column prop="goodsName" label="商品名称" align="center"> </el-table-column>
                <el-table-column prop="goodsCode" label="编号" align="center"> </el-table-column>
                <el-table-column prop="primaryClassify" label="分类" align="center"></el-table-column>
                <el-table-column prop="price" label="价格" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" class="delete" @click.native.prevent="deleteRowByMoney(scope.$index, tableDataByMoney)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="formFoot">
              <el-form-item label="" label-width="0">
                <el-button type="primary" v-if="setRole('获取保存')" @click="saveByMoney('getFormData')">保存</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>

        <!-- 按商品积分 -->
        <div v-show="getFormData.integralType == 1">
          <el-form :model="getFormData" :rules="getRules" ref="getFormData" :inline="true" size="mini">
            <div>
              <el-form-item label="" label-width="0"><span>设置积分商品</span></el-form-item>
              <el-form-item label="" label-width="0">
                <el-button type="primary" @click="clickAddGoodsByGoods()">添加 </el-button>
              </el-form-item>
            </div>
            <div class="tableMain">
              <el-table :data="tableDataByGoods" ref="tableDataByGoods" style="width: 100%" height="300">
                <el-table-column prop="goodsName" label="商品名称" align="center"> </el-table-column>
                <el-table-column prop="goodsCode" label="编号" align="center"> </el-table-column>
                <el-table-column prop="primaryClassify" label="分类" align="center"></el-table-column>
                <el-table-column prop="integral" label="积分数" align="center">
                  <template slot-scope="scope" align="center">
                    <el-input v-model="scope.row.integral" placeholder=">=1的整数" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" class="delete" @click.native.prevent="deleteRowByGoods(scope.$index, tableDataByGoods)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="formFoot">
              <el-form-item label="" label-width="0">
                <el-button type="primary" v-if="setRole('获取保存')" @click="saveByGoods('getFormData')">保存</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>

        <!-- 按消费金额添加弹窗 -->
        <el-dialog class="addshopname" title="不参加积分商品" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="dialogMoney" width="60%">
          <i class="el-icon-close icon" @click="dialogMoney = false"></i>
          <el-form size="mini">
            <el-form-item label="">
              <el-input placeholder="请输入商品名称" v-model="selectData.keywordMoney"></el-input>
              <el-button type="primary" @click="handleSearchMoney()">查询</el-button>
            </el-form-item>
          </el-form>
          <div class="tableMain">
            <el-table :data="tableDataDialogMoney" ref="tableDataDialogMoney" style="width: 100%" height="300" @selection-change="handleSelectionChangeMoney">
              <el-table-column type="selection" align="center" width="55"></el-table-column>
              <el-table-column property="goodsName" align="center" label="商品名称"> </el-table-column>
              <el-table-column property="goodsCode" align="center" label="编号"> </el-table-column>
              <el-table-column prop="primaryClassify" label="分类" align="center"></el-table-column>
              <el-table-column property="price" align="center" label="价格"></el-table-column>
              <el-table-column property="unitName" align="center" label="单位"></el-table-column>
            </el-table>
            <page-unit :pageData="pageDataDialogMoney" :func="getGoodsListByMoney"></page-unit>
            <div slot="footer" class="dialog-footer foot">
              <el-button type="primary" @click="clickDialogMoneySave()" size="mini">保存</el-button>
              <el-button @click="dialogMoney = false" size="mini">取 消</el-button>
            </div>
          </div>
        </el-dialog>

        <!-- 按商品积分添加弹窗 -->
        <el-dialog class="addshopname" title="添加积分商品" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="dialogGoods" width="60%">
          <i class="el-icon-close icon" @click="dialogGoods = false"></i>
          <el-form size="mini">
            <el-form-item label="">
              <el-input placeholder="请输入商品名称" v-model="selectData.keywordGoods"></el-input>
              <el-button type="primary" @click="handleSearchGoods()">查询</el-button>
            </el-form-item>
          </el-form>
          <div class="tableMain">
            <el-table :data="tableDataDialogGoods" style="width: 100%" height="300" ref="tableDataDialogGoods" @selection-change="handleSelectionChangeGoods">
              <el-table-column type="selection" align="center" width="55"></el-table-column>
              <el-table-column property="goodsName" align="center" label="商品名称"> </el-table-column>
              <el-table-column property="goodsCode" align="center" label="编号"> </el-table-column>
              <el-table-column prop="primaryClassify" label="分类" align="center"></el-table-column>
              <el-table-column property="price" align="center" label="价格"></el-table-column>
              <el-table-column property="unitName" align="center" label="单位"></el-table-column>
            </el-table>
            <page-unit :pageData="pageDataDialogGoods" :func="getGoodsListByGoods"></page-unit>
            <div slot="footer" class="dialog-footer foot">
              <el-button type="primary" @click="clickDialogGoodsSave()" size="mini">保存</el-button>
              <el-button @click="dialogGoods = false" size="mini">取 消</el-button>
            </div>
          </div>
        </el-dialog>
      </el-tab-pane>

      <el-tab-pane label="积分消费" name="积分消费">
        <el-form ref="consumeFormData" :model="consumeFormData" size="mini" :inline="true">
          <el-form-item label="" label-width="0">
            <el-checkbox-group v-model="consumeFormData.type" @change="handleIsCash">
              <el-checkbox label="0" value="0" name="type">抵现</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="" label-width="0">
            <el-input type="text" onkeyup="this.value=this.value.replace(/\D|^0/g,'')" onafterpaste="this.value=this.value.replace(/\D|^0/g,'')" :disabled="isDisabledConsume" v-model="consumeFormData.integral"></el-input>
          </el-form-item>
          <el-form-item label="" label-width="0">
            <div class="integral-title">积分 = <b>1</b> 元</div>
          </el-form-item>
        </el-form>
        <el-button size="mini" v-if="setRole('消费保存')" @click="handleSaveConsume()" type="primary">保存</el-button>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import u from "@/util";
import { mapState } from "vuex";
import pageUnit from "@/components/Page";
import {
  getMarketRules,
  getMarketRuleGoods,
  saveMarketConsumRules,
  findGoodsListPage,
  getCompanySupplierList,
  getBrandList,
  getGoodsClassifyList,
  saveMarketGainRules,
} from "@/api";
export default {
  computed: mapState(["sub", "power", "merchantId", "linkName" ,"mobile"]),
  components: { pageUnit },
  data() {
    return {
      activeName: '积分获取',  // 激活的tab
      getFormData: {
        getId: '',  // 主键id
        integralType: '0',  // 积分方式，0:按消费金额，1:按商品积分
        amount: '',  // 消费amount元积1分
      },
      getRules: {
        amount: [
          { required: true, message: '请输入积分', trigger: 'blur'},
          { validator: u.validatenum1, trigger: 'blur'},
          { validator: u.validatenum, trigger: 'blur'}
        ]
      },
      selectTableMoney: [], // 
      selectTableGoods: [], // 
      tableDataByMoney: [],  // 
      tableDataByGoods: [],  // 
      tableDataDialogMoney: [],  // 
      tableDataDialogGoods: [],  // 
      dialogMoney: false,  // 
      dialogGoods: false,  //
      selectData: {
        keywordMoney: '',
        keywordGoods: ''
      },
      pageDataDialogMoney: {
        pageSize: 20,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      pageDataDialogGoods: {
        pageSize: 20,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      isDisabledConsume: false,
      consumeFormData: {  // 积分消费的formdata
        consumeId: "",  // 积分消费主键id
        integral: "",  // 积分值
        type: true,  // 是否抵现
        consumeType: ""  // 消费类型
      },
    };
  },
  mounted() {
    this.lookDetailGet();
  },
  methods: {
    // tab切换
    handleTabChange(tab, event) {
      if(tab.name == '积分获取') {
        this.lookDetailGet();
      }
      if(tab.name == '积分消费') {
        this.lookDetailConsume();
      }
    },
    setRole (key) {
      return u.selectTitle(this.power, key)
    },
    // 切换积分获取方式
    handleChangeIntegralType(val) {
      // console.log(val)
    },
    // 点击添加不参加积分商品
    clickAddGoodsByMoney() {
      this.getGoodsListByMoney(this.pageDataDialogMoney.pageSize, 1);
      this.dialogMoney = true;
    },
    clickAddGoodsByGoods() {
      this.getGoodsListByGoods(this.pageDataDialogGoods.pageSize, 1);
      this.dialogGoods = true;
    },
    handleSearchMoney() {
      this.getGoodsListByMoney(this.pageDataDialogMoney.pageSize, 1)
    },
    handleSearchGoods() {
      this.getGoodsListByGoods(this.pageDataDialogGoods.pageSize, 1)
    },
    handleSelectionChangeMoney(val) {
      this.selectTableMoney = val;
    },
    handleSelectionChangeGoods(val) {
      this.selectTableGoods = val;
    },
    deleteRowByMoney(index, rows) {
      rows.splice(index, 1);
    },
    deleteRowByGoods(index, rows) {
      rows.splice(index, 1);
    },
    getGoodsListByMoney(pageSize, pageNum) {
      let data = {
        name: this.selectData.keywordMoney,
        pageNo: pageNum,
        pageSize: pageSize,
        shopId: this.merchantId,
        status: '0',
      };
      findGoodsListPage(data).then(res => {
        res.data.list.forEach(i => {
          i.goodsName = i.name
          i.price = i.goodsPrice
        })
        this.tableDataDialogMoney = res.data.list
        this.pageDataDialogMoney.totalItems = res.data.total
      })
    },
    getGoodsListByGoods(pageSize, pageNum) {
      let data = {
        name: this.selectData.keywordGoods,
        pageNo: pageNum,
        pageSize: pageSize,
        shopId: this.merchantId,
        status: '0',
      };
      findGoodsListPage(data).then(res => {
        res.data.list.forEach(i => {
          i.goodsName = i.name
          i.price = i.goodsPrice
        })
        this.tableDataDialogGoods = res.data.list
        this.pageDataDialogGoods.totalItems = res.data.total
      })
    },
    clickDialogMoneySave() {
      this.selectTableMoney.forEach(i => {
        i.goodsId = i.id
      })
      this.tableDataByMoney = this.tableDataByMoney.concat(this.selectTableMoney)
      for(let i = 0; i < this.tableDataByMoney.length-1; i++) {
        for(let j = i+1; j < this.tableDataByMoney.length; j++) {
          if(this.tableDataByMoney[i].goodsId === this.tableDataByMoney[j].goodsId) {
            this.tableDataByMoney.splice(j, 1);
          }
        }
      }
      this.dialogMoney = false
    },
    clickDialogGoodsSave() {
      this.selectTableGoods.forEach(i => {
        i.goodsId = i.id
      })
      this.tableDataByGoods = this.tableDataByGoods.concat(this.selectTableGoods)
      for(let i = 0; i < this.tableDataByGoods.length-1; i++) {
        for(let j = i+1; j < this.tableDataByGoods.length; j++) {
          if(this.tableDataByGoods[i].goodsId === this.tableDataByGoods[j].goodsId) {
            this.tableDataByGoods.splice(j, 1);
          }
        }
      }
      this.dialogGoods = false
    },
    // 保存积分获取规则-按照消费金额
    saveByMoney(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if(this.tableDataByMoney == undefined) {
            this.tableDataByMoney = []
          }
          if(Number(this.getFormData.amount) > 99 || 
          Number(this.getFormData.amount) < 0 || 
          Number(this.getFormData.amount == 0) || 
          this.getFormData.amount == '') {
            this.$message.error('输入积分格式不正确！');
            return false
          }
          var data = {
            companyId: this.merchantId,
            gainType: this.getFormData.integralType,  // 积分方式
            amount: this.getFormData.amount,  // 积分兑换金额
            gainGoods: this.tableDataByMoney,  // 商品数组
            id: this.getFormData.getId  // 修改时的主键id
          }
          saveMarketGainRules(data).then(res => {
            if(res.code == 200) {
              this.$message.success(res.msg)
              this.lookDetailGet();
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    saveByGoods(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let integral = 0
          for (let i = 0; i < this.tableDataByGoods.length; i++) {
            if (/^[1-9]\d*$/.test(this.tableDataByGoods[i].integral)) {
              integral += 1
            }
          }
          if (integral == this.tableDataByGoods.length) {
            if (this.tableDataByGoods == undefined) {
              this.tableDataByGoods = []
            }
            var data = {
              companyId: this.merchantId,
              gainType: this.getFormData.integralType,
              amount: '',
              gainGoods: this.tableDataByGoods,
              id: this.getFormData.getId
            }
            saveMarketGainRules(data).then(res => {
              if(res.code == 200) {
                this.$message.success(res.msg)
                this.lookDetailGet();
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            this.$message({
              type: 'error',
              message: '请检查积分数'
            })
          }
        }
      })
    },
    // 查看详情
    lookDetailGet() {
      let data = {
        companyId: this.merchantId,
        pageSize: 20,
        pageNum: 1,
        type: 0,
        keyword: ''
      }
      getMarketRules(data).then(res => {
        if (res.data != null) {
          this.getFormData.getId = res.data.id;  // 新增一条后的主键id
          this.getFormData.integralType = res.data.gainType.toString();  // 积分方式
          if (res.data.gainType == 0) {  // 积分方式-按消费金额
            this.getFormData.amount = res.data.amount
            this.tableDataByMoney = res.data.gainGoods
            this.tableDataByGoods = []
          } else {  // 积分方式-按商品积分
            this.getFormData.amount = 0
            this.tableDataByMoney = []
            this.tableDataByGoods = res.data.gainGoods
          }
        }
      })
    },
    // 积分抵现切换
    handleIsCash(val) {
      if (val) {
        this.isDisabledConsume = false;
      } else {
        this.isDisabledConsume = true;
      }
    },
    lookDetailConsume() {
      let data = {
        companyId: this.merchantId,
        type: 1  // 积分类型，积分消费
      };
      getMarketRules(data).then(res => {
        if (res.data != null) {
          this.consumeFormData.consumeId = res.data.id;  // 主键id
          // 消费类型  0-抵现，1-换购
          if (res.data.consumeType == 0) {
            this.consumeFormData.type = true;
            this.isDisabledConsume = false;
            this.consumeFormData.integral = res.data.integral;  // 积分值
          } else if (res.data.consumeType == 1) {
            this.consumeFormData.type = false;
            this.isDisabledConsume = true;
            this.consumeFormData.integral = 0;  // 积分值
          }
        }
      });
    },
    // 保存积分获取规则 按照消费金额
    handleSaveConsume() {
      if(this.consumeFormData.type == true) {
        this.consumeFormData.consumeType = 0;  // 抵现
      } else {
        this.consumeFormData.consumeType = 1;  // 换购
        this.consumeFormData.integral = 0;
      }
      let data = {
          consumRule: {
            companyId: this.merchantId,
            consumeType: this.consumeFormData.consumeType,
            integral: this.consumeFormData.integral,  // 积分
            id: this.consumeFormData.consumeId,
          }
      }
      saveMarketConsumRules(data).then(res => {
          if(res.code == 200) {
            this.$message.success(res.msg)
            this.lookDetailConsume();
          } else {
            this.$message.error(res.msg)
          }
      });
    },
    // 数组去重，不能有同一id
    uniqueArr(arr){
      arr.sort()
      var hash = [];
      var temp=[arr[0]];
      for(var i = 1; i < arr.length; i++){
        if( arr[i].id !== temp[temp.length-1].id){
            temp.push(arr[i]);
        }
      }
      return temp;
    }
  }
};
</script>
<style scoped>
.formFoot {
  margin-top: 15px;
}
</style>
